package tool

import (
	"fmt"
	"github.com/go-redis/redis"
	"log"
	"strings"
	"time"
)

const (
	CaptchaExpireTime = time.Minute * 10
)

var GlobalRedisStore RedisStore

type RedisStore struct {
	client *redis.Client
}

func (rs *RedisStore) Set(id string, value string) error {
	status := rs.client.Set(id, value, CaptchaExpireTime)
	err := status.Err()
	if err != nil {
		log.Printf("redis set error: %v", err)
	}
	return err
}

func (rs * RedisStore) Get(id string, clear bool) string {
	value, err := rs.client.Get(id).Result()
	if err != nil {
		log.Printf("redis miss: %v", err)
		return ""
	}
	if clear {
		if err := rs.client.Del(id).Err(); err != nil {
			log.Printf("redis del error: %v", err)
		}
	}
	return value
}

func (rs * RedisStore) Verify(id, answer string, clear bool) bool {
	v := rs.Get(id, clear)
	if answer == "" {
		return false
	}
	return strings.EqualFold(v, strings.TrimSpace(answer))
}

func InitRedisStore() *RedisStore {
	config := GetConfig().Redis
	client := redis.NewClient(&redis.Options{
		Addr: fmt.Sprintf("%s:%s", config.Host, config.Port),
		Password: config.Password,
		DB: config.Db,
	})
	GlobalRedisStore = RedisStore{client: client}
	return &GlobalRedisStore
}

